package bean.control;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import com.google.appengine.api.datastore.Text;

import bean.entity.DiscussContent;
import bean.entity.Discussion;
import bean.entity.Member;
import bean.entityField.DiscussionField;
import bean.persistence.PersistenceHelper;

public class DiscussionMgr {
	public static void addDiscussion(String question, long memId) {
		PersistenceHelper pHelper = new PersistenceHelper();
		
		pHelper.openPersistence();
		try {
			Member mem = (Member)pHelper.getById(Member.class, memId);
			Date now = new Date();
			List<DiscussContent> discussContents = new LinkedList<DiscussContent>();
			DiscussContent disContent = new DiscussContent(null, new Text(question), now, mem);
			Discussion dis;
			
			discussContents.add(disContent);
			dis = new Discussion(null, discussContents, now);
			pHelper.insert(dis);
		} finally {
			pHelper.closePersistence();
		}
	}
	
	@SuppressWarnings("unchecked")
	public static List<Discussion> queryAllDiscussionOrderByTime() {
		PersistenceHelper pHelper = new PersistenceHelper();
		
		pHelper.openPersistence();
		pHelper.openQuery(Discussion.class);
		try {
			List<Discussion> disList = (List<Discussion>)pHelper.query(null, DiscussionField.LATESTTIME + " desc", null, null, null);
			List<Discussion> copyDisList = new LinkedList<Discussion>();
			
			for (Discussion dis: disList) {
				List<DiscussContent> discussContents = dis.getDiscussContents();
				List<DiscussContent> copyDiscussContents = new LinkedList<DiscussContent>();
				Discussion copyDis;
				
				for (DiscussContent disContent: discussContents) {
					Member mem = disContent.getPoMember();
					Member copyMem = null;
					DiscussContent copyDisContent;
					
					if (mem != null)
						copyMem = new Member(mem.getKey(), mem.getStuNum(), mem.getName(), mem.getPassword(), mem.getState());
					copyDisContent = new DiscussContent(disContent.getKey(), disContent.getContent(), disContent.getTime(), copyMem);
					copyDiscussContents.add(copyDisContent);
				}
					
				copyDis = new Discussion(dis.getKey(), copyDiscussContents, dis.getLatestTime());
				copyDisList.add(copyDis);
			}
			return copyDisList;
		} finally {
			pHelper.closeQuery();
			pHelper.closePersistence();
		}
	}
	
	public static void updateDiscussContentById(long memId, String content, long disId) {
		PersistenceHelper pHelper = new PersistenceHelper();
		
		pHelper.openPersistence();
		try {
			Member mem = null;
			Discussion dis = (Discussion)pHelper.getById(Discussion.class, disId);
			Date now = new Date();
			DiscussContent disContent;
			
			if (memId != 0)
				mem = (Member)pHelper.getById(Member.class, memId);
			disContent = new DiscussContent(null, new Text(content), now, mem);
			dis.getDiscussContents().add(disContent);
			dis.setLatestTime(now);
		} finally {
			pHelper.closePersistence();
		}
	}
}
